package com.xu.controller;

import com.xu.enums.OrderStatusEnum;
import com.xu.enums.PayMethod;
import com.xu.pojo.UserAddress;
import com.xu.pojo.bo.AddressBO;
import com.xu.pojo.bo.ShopcartBO;
import com.xu.pojo.bo.SubmitOrderBO;
import com.xu.pojo.vo.MerchantOrdersVO;
import com.xu.pojo.vo.OrderVO;
import com.xu.service.AddressService;
import com.xu.service.OrderService;
import com.xu.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author anan
 * @create 2022-02-24 9:41
 */
@RestController
@RequestMapping("orders")
@Api(value = "订单相关", tags = "订单相关的api接口")
public class OrderController extends BaseController{

    @Autowired
    private OrderService orderService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RedisOperator redisOperator;

    @ApiOperation(value = "用户下单", notes = "用户下单", httpMethod = "POST")
    @PostMapping("/create")
    public JSONResult create(
            @RequestBody SubmitOrderBO submitOrderBO,
            HttpServletRequest request,
            HttpServletResponse response) {

        /*System.out.println(submitOrderBO.toString());*/
        if (submitOrderBO.getPayMethod() != PayMethod.WEIXIN.type
                && submitOrderBO.getPayMethod() != PayMethod.ALIPAY.type ) {
            return JSONResult.errorMsg("支付方式不支持！");
        }
        String shopcartJson = redisOperator.get(FOODIE_SHOPCART + ":" + submitOrderBO.getUserId());
        if (StringUtils.isBlank(shopcartJson)) {
            return JSONResult.errorMsg("购物数据不正确");
        }
        List<ShopcartBO> shopcartList = JsonUtils.jsonToList(shopcartJson, ShopcartBO.class);

        // 1、创建订单
        OrderVO orderVO = orderService.createOrder(shopcartList, submitOrderBO);
        String orderId = orderVO.getOrderId();

        // 2、创建订单以后，移除购物车中已结算(已提交) 的商品

        //清理覆盖现有的redis汇总的购物数据
        shopcartList.removeAll(orderVO.getToBeRemovedShopcartList());
        redisOperator.set(FOODIE_SHOPCART + ":" + submitOrderBO.getUserId(), JsonUtils.objectToJson(shopcartList));

        CookieUtils.setCookie(request, response, FOODIE_SHOPCART, JsonUtils.objectToJson(shopcartList), true);
        // 3、向支付中心发送当前订单，用于保存支付中心的订单数据
        MerchantOrdersVO merchantOrdersVO = orderVO.getMerchantOrdersVO();
        merchantOrdersVO.setReturnUrl(payReturnUrl);

        //为了方便测试，所有的支付金额统一改为1分钱
        merchantOrdersVO.setAmount(1);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("imoocUserId", "imooc");
        headers.add("password", "imooc");
        HttpEntity<MerchantOrdersVO> entity = new HttpEntity<>(merchantOrdersVO, headers);
        ResponseEntity<JSONResult> responseEntity =
                restTemplate.postForEntity(paymentUrl,
                                            entity,
                                            JSONResult.class);
        JSONResult paymentResult = responseEntity.getBody();
        if(paymentResult.getStatus() != 200){
            System.out.println(paymentResult.getStatus() + "----------------------------==============================");
            return JSONResult.errorMsg("支付中心订单创建失败，请联系管理员！");
        }
        return JSONResult.ok(orderId);

    }
    @ApiOperation(value = "通知订单已支付", notes = "通知订单已支付", httpMethod = "POST")
    @PostMapping("/notifyMerchantOrderPaid")
    public Integer notifyMerchantOrderPaid(String merchantOrderId){
        orderService.updateOrderStatus(merchantOrderId, OrderStatusEnum.WAIT_DELIVER.type);
        return HttpStatus.OK.value();
    }
}
